import {
  Button,
  Col,
  Form,
  FormItem,
  Input,
  InputNumber,
  Modal,
  RadioGroup,
  Row,
  Space,
  Spin,
  Tag,
  TreeSelect
} from 'ant-design-vue'
import { omitBy } from 'lodash-unified'
import { defineComponent, onMounted, ref } from 'vue'

import { deptApi, dictApi } from '@/apis'
import { ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { TableOptions, useTableRef } from '@/hooks'
import { dictToOptions } from '@/utils'

import { useDeptTree, useOperation, useToolbar } from './hooks'
import type { DeptFormType } from './types'

export default defineComponent({
  name: 'DeptView',
  setup() {
    const statusOptions = ref([] as OptionItem[])
    const tableConfig = ref({
      loading: false,
      toolbarConfig: {
        custom: true,
        refresh: true,
        zoom: true,
        slots: {
          buttons: 'toolbar_buttons'
        }
      },
      formConfig: {
        items: [
          {
            field: 'deptName',
            title: '部门名称',
            itemRender: {
              name: TABLE_ITEM_RENDER.AInput,
              props: {
                placeholder: '请输入部门名称'
              }
            }
          },
          {
            field: 'status',
            title: '状态',
            itemRender: {
              name: TABLE_ITEM_RENDER.ASelect,
              props: {
                placeholder: '部门状态'
              }
            }
          },
          {
            itemRender: {
              name: TABLE_RENDERER.FormItemBtns
            }
          }
        ]
      },
      columns: [
        {
          field: 'deptName',
          title: '部门名称',
          treeNode: true
        },
        {
          field: 'orderNum',
          title: '排序'
        },
        {
          field: 'status',
          title: '状态',
          slots: {
            default: 'status'
          }
        },
        {
          field: 'createTime',
          title: '创建时间',
          formatter: TABLE_FORMAT.Date
        },
        {
          title: '操作',
          slots: {
            default: 'operation'
          }
        }
      ],
      proxyConfig: {
        seq: true,
        form: true,
        props: {
          result: 'list',
          total: 'total'
        },
        ajax: {
          query: async ({ form }) => {
            form = omitBy(form, value => {
              return value === null
            })

            const data = await deptApi.getDeptList({
              ...form
            })
            return data
          }
        }
      },
      treeConfig: {
        transform: true,
        rowField: 'deptId',
        parentField: 'parentId',
        expandAll: true
      }
    } as TableOptions)

    const tableRefHook = useTableRef(tableConfig)
    const { getDeptTree, ...deptTreeRestHook } = useDeptTree()
    const operationHook = useOperation({
      tableRefHook,
      getDeptTree
    })
    const toolbarHook = useToolbar({
      tableRefHook,
      getDeptTree
    })

    async function init() {
      const [dictStatus] = await Promise.all([
        dictApi.getDictDataList('sys_normal_disable')
      ])

      statusOptions.value = dictToOptions(dictStatus)

      tableRefHook.updateFormItem({
        field: 'status',
        key: 'itemRender.props.options',
        value: statusOptions.value
      })
    }

    onMounted(() => {
      init()
    })

    return {
      statusOptions,
      tableRef: tableRefHook.tableRef,
      tableConfig,
      ...deptTreeRestHook,
      ...operationHook,
      ...toolbarHook
    }
  },
  render() {
    const renderForm = (type: DeptFormType) => {
      const formModel = type === 'add' ? this.addFormModel : this.editFormModel
      const formRef = type === 'add' ? this.addFormRef : this.editFormRef

      return (
        <Modal
          title={type === 'add' ? '添加部门' : '修改部门'}
          visible={type === 'add' ? this.showAdd : this.showEdit}
          confirmLoading={type === 'add' ? this.addLoading : this.editLoading}
          onOk={type === 'add' ? this.handleAdd : this.handleEdit}
          onCancel={type === 'add' ? this.handleCloseAdd : this.handleCloseEdit}
          destroyOnClose
        >
          <Spin spinning={this.treeLoading}>
            <Form>
              <Row>
                <Col span={24}>
                  <FormItem
                    label={'上级部门'}
                    labelCol={{ span: 4 }}
                    {...formRef.validateInfos['parentId']}
                  >
                    <TreeSelect
                      v-model:value={formModel.parentId}
                      treeData={this.deptTree}
                      fieldNames={{
                        children: 'children',
                        label: 'title',
                        value: 'key'
                      }}
                      allowClear
                      placeholder={'请选择上级部门'}
                    />
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem
                    label={'部门名称'}
                    labelCol={{ span: 8 }}
                    {...formRef.validateInfos['deptName']}
                  >
                    <Input
                      v-model:value={formModel.deptName}
                      placeholder="请输入部门名称"
                    />
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem
                    label={'显示顺序'}
                    labelCol={{ span: 8 }}
                    {...formRef.validateInfos['orderNum']}
                  >
                    <InputNumber
                      v-model:value={formModel.orderNum}
                      style={{
                        width: '100%'
                      }}
                    />
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem label={'负责人'} labelCol={{ span: 8 }}>
                    <Input
                      v-model:value={formModel.leader}
                      placeholder="请输入负责人"
                    />
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem label={'联系电话'} labelCol={{ span: 8 }}>
                    <Input
                      v-model:value={formModel.phone}
                      placeholder="请输入联系电话"
                    />
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem label={'邮箱'} labelCol={{ span: 8 }}>
                    <Input
                      v-model:value={formModel.email}
                      placeholder="请输入邮箱"
                    />
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem label={'部门状态'} labelCol={{ span: 8 }}>
                    <RadioGroup
                      v-model:value={formModel.status}
                      options={this.statusOptions}
                    ></RadioGroup>
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </Spin>
        </Modal>
      )
    }

    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            toolbar_buttons: () => (
              <Space>
                <Button
                  v-permission="system:dept:add"
                  type={'primary'}
                  ghost
                  onClick={() => this.handleShowAdd()}
                >
                  新增
                </Button>
                <Button onClick={this.handleToggleExpand}>展开/折叠</Button>
              </Space>
            ),
            status: ({ row }) =>
              row.status === '1' ? (
                <Tag color={'red'}>停用</Tag>
              ) : (
                <Tag color={'blue'}>正常</Tag>
              ),
            operation: ({ row }) => (
              <Space size={'small'}>
                <Button
                  v-permission="system:dept:edit"
                  type={'link'}
                  size={'small'}
                  onClick={() => this.handleShowEdit(row)}
                >
                  修改
                </Button>
                <Button
                  v-permission="system:dept:add"
                  type={'link'}
                  size={'small'}
                  onClick={() => this.handleShowAdd(row.deptId)}
                >
                  新增
                </Button>
                {row.deptId !== '100' ? (
                  <Button
                    v-permission="system:dept:remove"
                    type={'link'}
                    size={'small'}
                    onClick={() => this.handleDelete(row.deptId)}
                  >
                    删除
                  </Button>
                ) : null}
              </Space>
            )
          }}
          {...this.tableConfig}
        />
        {/* 新增弹窗 */}
        {renderForm('add')}
        {/* 修改弹窗 */}
        {renderForm('edit')}
      </div>
    )
  }
})
